import { ElMessage } from 'element-plus';
import { deepCopy } from '/@/utils';
import { useProductApi } from '/@/api/product';
import { arrHasData } from '/@/utils';

const { getCateList, editCate } = useProductApi();

export const rules = {
	parentId: [{ required: true, trigger: 'change' }],
	name: [{ required: true, trigger: 'blur' }],
	score: [{ required: true, trigger: 'blur' }],
};

export const useInit = () => {
	const loading = ref(false);
	const tableData = ref([]);
	const cateType = ref('1');
	const searchForm = ref({
		status: -1,
	});

	const init = async () => {
		loading.value = true;
		let res = await getCateList(searchForm.value.status, Number(cateType.value));
		loading.value = false;
		if (res.code !== 200) return;
		tableData.value = res.data;
	};

	const handleClicTab = (tab) => {
		cateType.value = tab.props.name;
		init();
	};

	const changeStatus = async ({ id, showStatus }) => {
		let res = await editCate({ id, showStatus });
		if (res.code === 200) {
			ElMessage.success('更改状态成功！');
		} else {
			init();
		}
	};

	const levelFormat = (index) => ['一级分类', '二级分类', '三级分类', '四级分类'][index];

	return {
		init,
		changeStatus,
		levelFormat,
		handleClicTab,
		loading,
		tableData,
		cateType,
		searchForm,
	};
};

export const useAdd = () => {
	const isAdd = ref(false);
	const addDialogVisible = ref(false);

	const toAdd = () => {
		addDialogVisible.value = true;
		isAdd.value = true;
	};

	return {
		toAdd,
		addDialogVisible,
		isAdd,
	};
};

export const useEdit = (option) => {
	const itemInfo = ref({});

	const toEdit = (row) => {
		option.addDialogVisible.value = true;
		itemInfo.value = deepCopy(row);
		option.isAdd.value = false;
	};

	return {
		toEdit,
		itemInfo,
	};
};

export const useSearch = () => {
	const searchForm = ref({
		status: -1,
	});
	return {
		searchForm,
	};
};
export const usePic = (ruleForm) => {
	const isShowPicSelector = ref(false);

	return {
		isShowPicSelector,
		selectPic() {
			isShowPicSelector.value = true;
		},
		getPic(pic) {
			if (!arrHasData(pic)) return;
			ruleForm.value.icon = pic[0].imgUrl;
		},
	};
};
